﻿using System;
using HttpApiGateway.Interface;
using RpcCacheClient.Interface;
using RpcClient.Interface;
using RpcHelper;

namespace HttpApiGateway.Idempotent.Token
{
    [RpcClient.Attr.UnityName("Redis")]
    [RpcClient.Attr.ClassLifetimeAttr(RpcClient.Attr.ClassLifetimeType.单例)]
    internal class RedisTokenService : ITokenIdempotent
    {
        private readonly IIdentityService _Service;
        private readonly IRedisCache _Redis;
        private readonly IIdempotentConfig _Config;
        public RedisTokenService(IIdentityService service, IRedisCache redis, IIdempotentConfig config)
        {
            _Redis = redis;
            _Config = config;
            _Service = service;
        }
        public StatusSaveType SaveType => StatusSaveType.Redis;
        public void Dispose()
        {

        }
        public string ApplyToken()
        {
            long token = _Service.CreateId();
            return !_Redis.Add("Idempotent_" + token, token, new TimeSpan(0, 0, _Config.Expire))
                ? throw new ErrorException("gateway.idempotent.token.apply.fail")
                : token.ToString();
        }
        public bool SubmitToken(string tokenId)
        {
            string key = "Idempotent_" + tokenId;
            return _Redis.Remove(key);
        }
    }
}
